import { defineStore } from "pinia";
import { userLogin } from '@a/user'
import router from "@/router";
import cookie from '@/utils/cookie'
import { ElMessage } from "element-plus";
import { removerUser} from '@u/user'
const useUserStore = defineStore("user", {
  state: ():any => ({
    token: "",
    userInfo: {},
    role: ""
  }),
  actions: {
    // 发送请求登录
    async userLogin(params: {userName: string; password: string}){
      const res:any = await userLogin(params);
      if (res.code === 200) {
        this.token = res.data.token;
        this.userInfo = res.data.userInfo;
        this.role = res.data.role;
        cookie.set('token', res.data.token)
        cookie.set('role', res.data.role)
        ElMessage({
          type: 'success',
          message: '登录成功',
          onClose: () => {
            router.replace('/dashBoard')
          }
        })
      }
    },
    userLogout(){
      removerUser();
      router.go(0)
    }
  },
  persist: {
    storage: {
      setItem(key: any, value: any){
        cookie.set(key, value)
      },
      getItem(key: any){
        return cookie.get(key)
      }
    }
  }
})

export default useUserStore